﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using UnityEngine.UI;
using UnityEngine.Networking;
using UnityEngine.Events;


public class AutolaborManager : MonoBehaviour
{



    int localPort = 20591;

    static UdpClient udp;

    Thread beaconThread;

    Thread checkProcessThread;

    public bool foundAutolabor = false;

    private bool lastFound = false;


    public string autolaborIP = "";

    string beaconMessage = "autolabor is here!";


    [SerializeField]
    BaseLaunch[] launches;


    [SerializeField]
    GameObject uiPanel;


    delegate void ProcessStatusChange (string process, bool live);

    ProcessStatusChange processStatusChange;



    [SerializeField]
    UnityEvent whenHaveLaunchRunning;

    [SerializeField]
    UnityEvent whenNoLaunchRunning;


  




    private List<string> robotRunningProcess;


    void Start()
    {

        robotRunningProcess = new List<string>();

        udp = new UdpClient(localPort);

        beaconThread = new Thread(new ThreadStart(CheckBeacon));

        beaconThread.Start(); 



        InvokeRepeating("CheckRobotProcess", 1.5f, 2.0f);


     
        Screen.sleepTimeout = 0;

        MessageBox.ShowMessage("查找Autolabor机器人...");


        processStatusChange+=onProcessStatusChange;


        foreach (BaseLaunch launch in launches)
        {

            processStatusChange+=launch.OnRobotProcessChange;


        }

    }

   

    void onProcessStatusChange(string process, bool live)
    {

        if (robotRunningProcess.Count>0)
        {

         
            whenHaveLaunchRunning.Invoke();

        }else
        {

            whenNoLaunchRunning.Invoke();


        }



    }



    void OnApplicationQuit()
    {
        if (beaconThread != null)
        {
            beaconThread.Abort();
        }
    }


    void Update()
    {

        if (lastFound == false && foundAutolabor == true)
        {

            OnFoundAutolabor();

            lastFound = foundAutolabor;

        }



    }

    private void CheckBeacon()
    {

        while (true)
        {

            IPEndPoint remoteEP = null;
            byte[] data = udp.Receive(ref remoteEP);
            string text = Encoding.ASCII.GetString(data);

            if (foundAutolabor == false && text.Equals(beaconMessage))
            {
                autolaborIP = remoteEP.Address.ToString();

                foundAutolabor = true;

            }

            Thread.Sleep(1000);

        }



    }

    void CheckRobotProcess()
    {
        
            
        foreach (BaseLaunch launch in launches)
        {
                
            StartCoroutine(updateProcessStatus(launch.launchName));

        }



    }



    IEnumerator updateProcessStatus(string process)
    {

        string url = "http://" + autolaborIP + "/task?cmd=isrunning&process=" + process;



        UnityWebRequest www = UnityWebRequest.Get(url);

        yield return www.Send();

        if (www.isError == false)
        {
            
            string respone = www.downloadHandler.text;



            if (respone.Equals("yes"))
            {

                if (robotRunningProcess.Contains(process) == false)
                {

                    robotRunningProcess.Add(process);
                   
                    processStatusChange(process,true);



                }

            }
            else
            {

                if (robotRunningProcess.Contains(process) == true)
                {
                    robotRunningProcess.Remove(process);

                    processStatusChange(process,false);


                }


            }

           
        }
       

        


    }



    private void OnFoundAutolabor()
    {

        uiPanel.SetActive(true);


        foreach (BaseLaunch launch in launches)
        {
            
            launch.address = autolaborIP;

        }


        MessageBox.ShowMessage("发现Autolabor:" + autolaborIP);

        Debug.Log("Found Autolabor at:" + autolaborIP);


    }


    public void StartLaunch(string launchName)
    {

        MessageBox.ShowMessage("正在启动:" + launchName);

        Cmd("start&launch=" + launchName);
        
        foreach (BaseLaunch launch in launches)
        {

          

            if (launchName.Equals(launch.launchName))
            {
                

                launch.gameObject.SetActive(true);
                launch.address = autolaborIP;
               

            }
            else
            {
                
                launch.Disconnect();
                launch.gameObject.SetActive(false);

            }

        }


    }




    public void Poweroff()
    {
        MessageBox.ShowMessage("正在关机...");
        Cmd("poweroff");
        MessageBox.ShowMessage("请等待雷达停止旋转后再关闭电源");

        uiPanel.SetActive(false);
    

    }


    public void Exit()
    {


        Application.Quit();


    }







    public void Cmd(string cmd)
    {
        
        StartCoroutine(RequestCmd(cmd));

    }




    IEnumerator RequestCmd(string cmd)
    {



        string url = "http://" + autolaborIP + "/task?cmd=" + cmd;

        UnityWebRequest www = UnityWebRequest.Get(url);

        yield return www.Send();

        if (www.isError)
        {
            Debug.Log(www.error);
        }
        else
        {
            // Show results as text
            Debug.Log(www.downloadHandler.text);

            // Or retrieve results as binary data
            byte[] results = www.downloadHandler.data;
        }


    }




}
